<template>
  <view class="pageHeight flex flex-column align-center wh_750 bg_F5F5F5">
    <s-header-title ref="headerTitle" isDisplayBack title="家谱管理" is-fixed background="#FFFFFF"
                    @getPageHeight="getPageHeight" zIndex="10">
    </s-header-title>
    <view :style="{height:`${page.headerHeight}px`}"></view>
    <!-- 家谱信息 -->
    <view class="hW_25"></view>
    <view class="genealogicalInformation flex align-center">
      <view class="genealogicalInformation_left">
        <image class="genealogicalInformation_left_image" :src="`${IMG_URL}/index/genealogicalInformation.png`"></image>
      </view>
      <view class="genealogicalInformation_right ml_15">
        <!-- 家谱名称 -->
        <view class="name">
          {{ page.genealogicalInformation.title || '未设置家谱名称' }}
        </view>
        <!-- 发起人 -->
        <view class="initiator">
          发起人: {{ page.genealogicalInformation.username }}
        </view>
        <!-- 家谱号 -->
        <view class="initiator flex align-center">
          家谱号: {{ page.genealogicalInformation.code }}
          <view class="ml_15 flex align-center" style="color: #FF4206;" @click.stop="setCilpText">
            复制
            <image class="ml_4" style="width: 38rpx;  height: 38rpx;" :src="`${IMG_URL}/index/replication.png`"></image>
          </view>
        </view>
        <!-- 所属地区 -->
        <view class="initiator" v-if="!!page.genealogicalInformation.city">
          所属地区: {{ page.genealogicalInformation.city.split('-').join('') }}
        </view>
        <!-- 创建时间 -->
        <view class="initiator" v-if="!!page.genealogicalInformation.add_time">
          创建时间: {{ dayjs(page.genealogicalInformation.add_time * 1000).format('YYYY年MM月DD日') }}
        </view>
      </view>
    </view>
    <!-- 家谱名称 -->
    <view class="hW_20"></view>
    <gapbar title="家谱名称" @elementClick="modifyTheFamilyTreeName">
      <template v-slot:content>
        <view class="content">
          {{ page.genealogicalInformation.title }}
        </view>
      </template>
    </gapbar>
    <!-- 家谱简介 -->
    <view class="hW_20"></view>
    <gapbar title="家谱简介" @elementClick="editRemark">
      <template v-slot:content>
        <view class="content">
          {{ page.genealogicalInformation.remark }}
        </view>
      </template>
    </gapbar>
    <!-- 所属地区 -->
    <view class="hW_20"></view>
    <gapbar title="所属地区" @elementClick="changeARegion">
      <template v-slot:content v-if="!!page.genealogicalInformation.city">
        <view class="content flex flex-column align-end">
          <view>
            {{ page.genealogicalInformation.city.split('-').join('') }}
          </view>
          <view class="wh_380" style="text-align: end;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
            {{ page.genealogicalInformation.city_address }}
          </view>
        </view>
      </template>
      <template v-slot:content v-else>
        <view class="content">
          请选择所属地区
        </view>
      </template>
    </gapbar>
    <!-- 家谱二维码 -->
    <view class="hW_20"></view>
    <gapbar title="家谱二维码" @elementClick="shareFriendsAndFamily">
      <template v-slot:content>
        <image class="familyEdit_familyName_code mr_10 mt_8" :src="`${IMG_URL}/index/qrcode.png`"></image>
      </template>
    </gapbar>
    <!-- 家谱日志 -->
    <view class="hW_20"></view>
    <gapbar title="家谱日志" @elementClick="goGenealogyLogs"></gapbar>
    <!-- 树谱样式 -->
    <view class="hW_20"></view>
    <gapbar title="树谱样式"
            @elementClick="treeSpectrumStyle"
    ></gapbar>
    <!-- 字辈设置 -->
    <view class="hW_20"></view>
    <gapbar title="字辈设置"
            @elementClick="generationSetting"
    ></gapbar>
    <!-- 导出 -->
    <view class="hW_20"></view>
    <gapbar title="导出"
            @elementClick="derive"
    ></gapbar>
    <view v-if="page.genealogicalInformation.show_merge == 1" class="hW_20"></view>
    <gapbar title="合并家谱" v-if="page.genealogicalInformation.show_merge == 1"
            @elementClick="combinedFamilyTree"
    ></gapbar>
    <!-- 样式 -->
    <!--    <view  class=hW_20></view >-->
    <!--    <gapbar title="样式"></gapbar>-->
    <view class="hW_20"></view>
    <members-list margin="25rpx 0 0 0" title="发起人" :list="page.sponsorList"
                  :permissionsIndex="3"
                  :familyId="page.options.id"
                  :ownDetail="page.ownDetail" @classificationIsComplete="classificationIsComplete"></members-list>
    <members-list margin="25rpx 0 0 0" title="联合发起人" :list="page.coSponsorsList"
                  :permissionsIndex="3"
                  :familyId="page.options.id"
                  :ownDetail="page.ownDetail" @classificationIsComplete="classificationIsComplete"></members-list>
    <members-list margin="25rpx 0 0 0" title="管理员" :list="page.administratorList"
                  :permissionsIndex="3"
                  :familyId="page.options.id"
                  :ownDetail="page.ownDetail" @classificationIsComplete="classificationIsComplete"></members-list>
    <members-list margin="25rpx 0 0 0" title="仅查看" :list="page.viewOnlyList"
                  :permissionsIndex="3"
                  :familyId="page.options.id"
                  :ownDetail="page.ownDetail" @classificationIsComplete="classificationIsComplete"></members-list>
    <view class="hW_100"></view>
    <view class="familiesList_btn flex align-center justify-center" @click.stop="shareFriendsAndFamily">
      <text class="familiesList_btn_text">邀请亲友加入</text>
    </view>
    <view class="hW_50"></view>
    <view class="familyEdit_bottomBtn flex align-center justify-center mb_74" @click.stop="deleteGenealogy">
      <text class="familyEdit_bottomBtn_text">{{ page.genealogicalInformation.is_own == 1 ? '删除家谱' : '退出家谱' }}
      </text>
    </view>


    <!-- 名字修改 -->
    <first_popup ref="namePopUp">
      <template #content>
        <view class="familyMemberPopUp allColumnCenter">
          <view class="familyMemberPopUp_title mt_45">
            <view class="familyMemberPopUp_title_name">
              修改家谱名称
            </view>
          </view>
          <image class="familyMemberPopUp_icon z-1" :src="`${IMG_URL}/index/add_icon.png`"></image>
          <view class="familyMemberPopUp_editInfo flex align-center justify-between mt_64">
            <view class="familyMemberPopUp_editInfo_left flex align-center justify-center">
              <input type="text" v-model="page.namePopupFrom.title"
                     :placeholder="!!page.genealogicalInformation.title ? page.genealogicalInformation.title : '请输入家谱名称'"
                     placeholder-class="familyMemberPopUp_editInfo_placeholder"
                     :focus="suernameFocus">
            </view>
          </view>
        </view>
      </template>
    </first_popup>
    <!-- 选择现居地/祖籍地 -->
    <!--    <areaWindow ref="areaWindow" :cityShow="2" :display="areaWindowDisplay" :address="addressInfo"-->
    <!--                @submit="OnChangeAddress"-->
    <!--                @changeClose="changeClose"></areaWindow>-->
    <su-region-picker title="所属地区"
                      :show="page.areaWindowDisplay"
                      @cancel="page.areaWindowDisplay = false"
                      @confirm="onAddressConfirm"
    ></su-region-picker>
  </view>
</template>

<script setup>
  import { onLoad, onShow, onReady } from '@dcloudio/uni-app';
  import { computed, nextTick, reactive, ref } from 'vue';
  import sheep from '@/sheep';
  import HeaderTitle from '@/pages/genealogy/components/headerTitle.vue';
  import First_popup from '@/pages/genealogy/components/first_popup.vue';
  import Gapbar from '@/pages/genealogy/components/gapbar.vue';
  import dayjs from 'dayjs';
  import MembersList from '@/pages/genealogy/components/fmilyMembersList.vue';
  import SuRegionPicker from '@/sheep/ui/su-region-picker/su-region-picker.vue';

  const page = reactive({
    headerHeight: 0,
    options: {},
    // 家谱信息
    genealogicalInformation: {},
    memberList: [],
    sponsorList: [],
    coSponsorsList: [],
    administratorList: [],
    viewOnlyList: [],
    ownDetail: {},
    namePopupFrom: {
      title: '',
    },
    suernameFocus: false,
    areaWindowDisplay: false,
    addressInfo: [],
  });
  const IMG_URL = computed(() => sheep.$store('AI').sq_image_path);

  onLoad((options) => {
    page.options = options;
    sheep.$api.data.area().then((res) => {
      if (res.code === 1) {
        uni.setStorageSync('areaData', res.data);
      }
    });
  });

  onShow(async () => {
    nextTick(async () => {
      await getGenealogicalInformation();
      await getGenealogistInfo();
      console.log('page.options=>',page.options);
      if (!!page.options.is_flag && page.options.is_flag != 'false') {
        page.options.is_flag = false;
        shareFriendsAndFamily();
      }
    });
  });

  onReady(() => {

  });


  function getPageHeight(number) {
    page.headerHeight = number;
  }

  async function getGenealogistInfo() {
    let { data } = await sheep.$api.genealogy.getGenealogyMember({
      genealogy_id: page.options.id,
    });
    page.memberList = data;
    page.sponsorList = [];
    page.coSponsorsList = [];
    page.administratorList = [];
    page.viewOnlyList = [];
    page.memberList.forEach(item => {
      if (item.is_own == 1) {
        page.ownDetail = item;
      }
      if (item.authority == 3) {
        page.sponsorList.push(item);
      } else if (item.authority == 2) {
        page.coSponsorsList.push(item);
      } else if (item.authority == 1) {
        page.administratorList.push(item);
      } else {
        page.viewOnlyList.push(item);
      }
    });
  }

  async function getGenealogicalInformation() {
    let { data } = await sheep.$api.genealogy.getGenealogyInfo({
      genealogy_id: page.options.id,
    });
    page.genealogicalInformation = data;
  }

  const namePopUp = ref();

  async function modifyTheFamilyTreeName() {
    const { code, msg } = await sheep.$api.genealogy.checkAuth({
      genealogy_id: page.options.id,
      action: 'add',
    });
    if (code != 1) {
      sheep.$helper.toast(msg);
      return;
    }
    setTimeout(() => {
      page.namePopupFrom.title = page.genealogicalInformation.title;
      page.suernameFocus = true;
    }, 100);
    namePopUp._value.openPopup({
      title: '',
      showTitle: false,
      maskClick: false,
      popupBackground: true,
      confirm: async () => {
        if (!page.namePopupFrom.title) {
          uni.showToast({
            title: '家谱名称尚未填写',
            icon: 'none',
          });
          return;
        }
        let { code, msg } = await sheep.$api.genealogy.updateGenealogyInfo({
          id: page.options.id,
          title: page.namePopupFrom.title,
        });
        namePopUp._value.closePopup();
        await getGenealogicalInformation();
      },
    });
  }

  async function editRemark() {
    const { code, msg } = await sheep.$api.genealogy.checkAuth({
      genealogy_id: page.options.id,
      action: 'add',
    });
    if (code != 1) {
      sheep.$helper.toast(msg);
      return;
    }
    uni.setStorageSync('genealogyRemark', JSON.stringify({
      remark: page.genealogicalInformation.remark,
      id: page.options.id,
    }));
    sheep.$router.go('/pages/genealogy/editGenealogyRemark');
  }

  async function changeARegion() {
    const { code, msg } = await sheep.$api.genealogy.checkAuth({
      genealogy_id: page.options.id,
      action: 'add',
    });
    if (code != 1) {
      sheep.$helper.toast(msg);
      return;
    }
    // page.areaWindowDisplay = true;
    sheep.$router.go('/pages/extend/addressFill', { id: page.options.id });
    // uni.$on('onAddressConfirm',(e)=>{
    //   onAddressConfirm(e)
    // })
  }

  async function onAddressConfirm(e) {
    let { code, msg } = await sheep.$api.genealogy.updateGenealogyInfo({
      id: page.options.id,
      city: e.province_name + '/' + e.city_name + '/' + e.district_name,
    });
    await getGenealogicalInformation();
    page.areaWindowDisplay = false;
  }

  function shareFriendsAndFamily() {
    uni.setStorageSync('shareFamilyTreePoster', JSON.stringify({
      id: page.options.id,
      avatar: page.sponsorList[0].avatar,
      name: page.genealogicalInformation.title,
      code: page.genealogicalInformation.code,
      username: page.genealogicalInformation.username,
      add_time: page.genealogicalInformation.add_time,
      remark: page.genealogicalInformation.remark,
    }));
    sheep.$router.go('/pages/genealogy/genealogySharing');
  }

  function deleteGenealogy() {
    uni.showModal({
      title: `确定${page.genealogicalInformation.is_own == 1 ? '删除' : '退出'}该家谱吗？`,
      success: async (res) => {
        if (res.confirm) {
          let { code, msg } = await sheep.$api.genealogy.signOutGenealogy({
            genealogy_id: page.options.id,
          });
          if (code == 1) {
            sheep.$helper.toast(`${page.genealogicalInformation.is_own == 1 ? '删除' : '退出'}成功`);
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/message/matchmaking',
              });
            }, 1000);
          }
        }
      },
    });
  }

  function goGenealogyLogs() {
    uni.setStorageSync('genealogicalJournalName', JSON.stringify({
      name: page.genealogicalInformation.title,
      id: page.genealogicalInformation.id,
    }));
    sheep.$router.go('/pages/genealogy/genealogicalJournal');
  }

  function classificationIsComplete() {
    page.sponsorList = [];
    page.coSponsorsList = [];
    page.administratorList = [];
    page.viewOnlyList = [];
    getGenealogicalInformation();
    getGenealogistInfo();
  }

  function setCilpText() {
    uni.setClipboardData({
      data: `家谱名称：${page.genealogicalInformation.title}
家谱号：${page.genealogicalInformation.code}`,
      showToast: '复制成功',
    });
  }

  async function generationSetting() {
    const { code, msg } = await sheep.$api.genealogy.checkAuth({
      genealogy_id: page.options.id,
      action: 'add',
    });
    if (code != 1) {
      sheep.$helper.toast(msg);
      return;
    }
    sheep.$router.go('/pages/genealogy/generation', { id: page.options.id });
  }

  function combinedFamilyTree() {
    sheep.$router.go('/pages/genealogy/combinedFamilyTree', {
      id: page.genealogicalInformation.code,
      genealogy_id: page.options.id,
    });
  }

  async function treeSpectrumStyle() {
    const { code, msg } = await sheep.$api.genealogy.checkAuth({
      genealogy_id: page.options.id,
      action: 'add',
    });
    if (code != 1) {
      sheep.$helper.toast(msg);
      return;
    }
    sheep.$router.go('/pages/genealogy/patternTreeSpectrum', { id: page.options.id });
  }

  function derive() {
    sheep.$router.go('/pages/public/richtext', {
      id: 15,
      title: '导出',
      genealogy_id: page.options.id,
    });
  }
</script>


<style scoped lang="scss">
  .genealogicalInformation {
    width: 702rpx;
    padding: 23rpx 15rpx;
    background: #FFFFFF;
    border-radius: 15rpx 15rpx 15rpx 15rpx;

    .genealogicalInformation_left {
      width: 170rpx;
      height: 170rpx;
      overflow: hidden;

      .genealogicalInformation_left_image {
        width: 170rpx;
        height: 170rpx;
      }
    }

    .genealogicalInformation_right {
      .name {
        font-family: PingFang SC, PingFang SC;
        font-weight: bold;
        font-size: 36rpx;
        color: #4B4B4B;
      }

      .initiator {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 28rpx;
        color: #4B4B4B;
      }
    }
  }

  .content {
    font-family: PingFang SC, PingFang SC;
    font-weight: 500;
    font-size: 28rpx;
    color: #4B4B4B;
  }

  .familyEdit_familyName_code {
    width: 30rpx;
    height: 30rpx;
  }

  .familyMemberPopUp {
    width: 506rpx;

    .familyMemberPopUp_title {
      width: 454rpx;

      .familyMemberPopUp_title_name {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 48rpx;
        color: #292929;

      }

      .familyMemberPopUp_title_detail {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 24rpx;
        color: #9F9F9F;
      }
    }

    .familyMemberPopUp_icon {
      width: 147rpx;
      height: 147rpx;
      position: absolute;
      top: 0;
      right: 0;
    }

    .familyMemberPopUp_scrollView {
      width: 506rpx;
      overflow: hidden;
      white-space: nowrap;

      .familyMemberPopUp_scrollView_list {
        display: inline-block;
      }
    }

    .familyMemberPopUp_editInfo {
      width: 506rpx;

      .familyMemberPopUp_editInfo_left {
        width: 510rpx;
        height: 80rpx;
        background: #FFFFFF;
        border-radius: 40rpx 40rpx 40rpx 40rpx;
        border: 2rpx solid #707070;

        input {
          text-align: center;
        }
      }

      .familyMemberPopUp_editInfo_placeholder {
        font-family: PingFang SC, PingFang SC;
        font-weight: 500;
        font-size: 28rpx;
        color: #A0A0A0;
      }
    }
  }

  .familiesList_btn {
    width: 470rpx;
    height: 80rpx;
    background: #FF4206;
    border-radius: 50rpx 50rpx 50rpx 50rpx;

    &_text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 30rpx;
      color: #FFFFFF;
    }
  }

  .familyEdit_bottomBtn {
    width: 470rpx;
    height: 80rpx;
    background: #F5F5F5;
    border-radius: 40rpx 40rpx 40rpx 40rpx;
    border: 2rpx solid #A0A0A0;

    &_text {
      font-family: PingFang SC, PingFang SC;
      font-weight: 500;
      font-size: 30rpx;
      color: #A0A0A0;
    }
  }
</style>
